package com.yyfax.ph.personal.authority.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.yyfax.common.form.LoginLayout;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.common.tools.SoftKeyboardUtils;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.forgot.ForgotPwdActivity;
import com.yyfax.ph.personal.authority.register.RegisterActivity;
import com.yyfax.ph.web.WebActivity;

public class LoginActivity extends BaseYYFaxActivity implements LoginPresenter.View, TextWatcher {

	private static final String TAG = LoginActivity.class.getSimpleName();

	private static final int LOADER_ID_LOGIN = 901;
	private static final String PHONE_NUMBER_KEY = "phone_number";
	private static final String PASSWORD_KEY = "password_number";
	private static final String CLEAR_GESTURE = "clear_gesture";
	private static boolean mIsForResult;

	@BindView(R.id.login_layout)
	LoginLayout mPhone;
	@BindView(R.id.password_layout)
	LoginLayout mPwd;
	@BindView(R.id.login_tv)
	Button mLoginBtn;
	@BindView(R.id.agreement_text)
	TextView mAgreementText;

	LoginPresenter mLoginPresenter;

	/**
	 * 登录成功之后清除手势密码
	 */
	private boolean mClearGesture;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, LoginActivity.class);
		aty.startActivity(intent);
	}

	public static void startActivityForResult(Activity aty, int requestCode) {
		Intent intent = new Intent(aty, LoginActivity.class);
		mIsForResult = true;
		aty.startActivityForResult(intent,requestCode);
	}

	public static void start(Activity aty, boolean clearGesture) {
		Intent intent = new Intent(aty, LoginActivity.class);
		intent.putExtra(CLEAR_GESTURE, clearGesture);
		aty.startActivity(intent);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new LoginPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mLoginPresenter = (LoginPresenter) data;
		mLoginPresenter.attach(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(LOADER_ID_LOGIN, null, this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOGIN);
	}

	@Override
	protected void onPause() {
		super.onPause();
		SoftKeyboardUtils.hideKeyboard(this);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.login_activity_layout;
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(true);
		setTitleVisible(true);
		setTitleLeftVisible(false);
		setBtnRightTx(R.string.register);
		setTitle(R.string.login);

		mTitleCenter.setTextSize(TypedValue.COMPLEX_UNIT_PX, DensityUtil.dip2px(this, 18));
		mBtnRightTx.setTextSize(TypedValue.COMPLEX_UNIT_PX, DensityUtil.dip2px(this, 15));
		mTitleCenter.setTextColor(getResources().getColor(R.color.color_262932));
		mBtnRightTx.setTextColor(getResources().getColor(R.color.color_f05b47));
		mBtnBack.setImageDrawable(getResources().getDrawable(R.drawable.btn_login_back));

		mPhone.addTextChangedListener(this);
		mPwd.addTextChangedListener(this);

		String userName = YJPH.getInstance().getPreferenceManager().getUserPhone();
		if (!TextUtils.isEmpty(userName)) {
			mPhone.setText(userName);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String userName = YJPH.getInstance().getPreferenceManager().getUserPhone();
		if (!TextUtils.isEmpty(userName)) {
			mPhone.setText(userName);
		}
		mPwd.setText("");
		mClearGesture = intent.getBooleanExtra(CLEAR_GESTURE, false);
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		RegisterActivity.start(this);
	}

	@OnClick({R.id.login_tv, R.id.forget_password_tv, R.id.agreement_tv})
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.login_tv:
				mLoginPresenter.login(mPhone.getText().toString().trim(), mPwd.getText().toString().trim());
				break;
			case R.id.forget_password_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E040);
				ForgotPwdActivity.start(this);
				break;
			case R.id.agreement_tv:
				WebActivity.start(this, getString(R.string.protocol_tx), WebActivity.TYPE_REGISTRATION_AGREEMENT);
				break;
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		inputWatch();
	}

	@Override
	public void afterTextChanged(Editable s) {
		inputWatch();
	}

	private void inputWatch() {
		String phoneInput = mPhone.getText().toString().trim();
		//登录密码为了兼容老的密码  不要求是字母和数字组合 只要长度大于6 小于20就行
		String passwordInput = mPwd.getText().toString().trim();
		if (!TextUtils.isEmpty(phoneInput) && !TextUtils.isEmpty(passwordInput)) {
			if (RegexUtil.isMobileNumber(phoneInput) && passwordInput.length() >= 6) {
				mLoginBtn.setEnabled(true);
			} else {
				mLoginBtn.setEnabled(false);
			}
		} else {
			mLoginBtn.setEnabled(false);
		}

	}

	@Override
	public void userLoginSuccess() {
		loginSuccess();
	}

	@Override
	public void userLoginFailure(String tips) {
		showToast(tips);
	}

	private void loginSuccess() {
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_FIRST_LOGIN_FLAG, true);
		if (mClearGesture) {//忘记手势密码时，登录成功后清除手势密码
			YJPH.getInstance().clearGesture(false);
		}
		if (mIsForResult) {
			setResult(RESULT_OK);
		} else {
			MainActivity.start(this);
		}
		finish();
	}

	@Override
	public int getTopBarBackgroundColor() {
		return ContextCompat.getColor(this, R.color.color_fafdff);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(PHONE_NUMBER_KEY, mPhone.getText().toString());
		outState.putString(PASSWORD_KEY, mPwd.getText().toString());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			restoreView(savedInstanceState);
		}
		mClearGesture = getIntent().getBooleanExtra(CLEAR_GESTURE, false);
	}

	private void restoreView(Bundle savedInstanceState) {
		String phoneNumber = savedInstanceState.getString(PHONE_NUMBER_KEY);
		String passWord = savedInstanceState.getString(PASSWORD_KEY);
		mPhone.setText(phoneNumber);
		mPwd.setText(passWord);
	}

}
